from Tkinter import *
from PIL import ImageTk
from MVC.plstdocument import IDocument
from service.PlusterLog import PlusterLog
from service.pconfig import PConfig
from service.rrd import Rrd
import os.path

class InfoView(Frame,PlusterLog):
    def __init__(self,ctl):
        PlusterLog.__init__(self)
        self.ctl=ctl
        #self.log.info("InfoView Created")

    def show(self,master=None):
        self.w = Toplevel(master)  # Use Toplevel to create a new window
        # in tkinter.   Toplevel creates a new window but no content.
        # Everything should be drawn in a Frame.  So InfoView is a frame.
        Frame.__init__(self,self.w)
        self.master.title("Node Information Task")
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        """Create Widgets.  If you want to change or add
        new widgets, please read tkinter.pdf for more info."""
        self.l_name=Label(self,text="Node name:")
        self.l_name.grid(row=0,column=0,sticky=W)
        self.l_ip=Label(self,text="Node IP:",width=26)
        self.l_ip.grid(row=0,column=1)
        self.l_mac=Label(self,text="Node MAC:",width=26)
        self.l_mac.grid(row=0,column=2)
        self.l_time=Label(self,text="Start Time: ")
        self.l_time.grid(row=1,sticky=W)
        self.l_port=Label(self,text="Port:")
        self.l_port.grid(row=1,column=2)
        self.l_cpu=Label(self,text="Cpu:")
        self.l_cpu.grid(row=2,column=0,sticky=W)
        self.l_mem=Label(self,text="Total Mem:")
        self.l_mem.grid(row=2,column=1)
        self.l_2=Label(self,text="Time span of report:")
        self.l_2.grid(row=4,sticky=W)
        self.radio_var=StringVar()
        self.radio1=Radiobutton(self,variable=self.radio_var,\
                               value="hour",text="1 hour",\
                                command=self.change_time)
        self.radio1.select()
        self.radio1.grid(row=4,column=1,sticky=W)
        self.radio2=Radiobutton(self,variable=self.radio_var,\
                               value="day",text="1 day",\
                                command=self.change_time)
        self.radio2.grid(row=4,column=2,sticky=W)
        self.radio3=Radiobutton(self,variable=self.radio_var,\
                               value="week",text="1 week",\
                                command=self.change_time)
        self.radio3.grid(row=5,column=1,sticky=W)
        self.radio4=Radiobutton(self,variable=self.radio_var,\
                               value="month",text="3 months",\
                                command=self.change_time)
        self.radio4.grid(row=5,column=2,sticky=W)
        self.canvas=Canvas(self,height=650,width=481,scrollregion=(0,0,650,481))
        self.canvas.grid(row=6,column=0,columnspan=4,sticky=N)

    def change_time(self,event=None):
        time=self.radio_var.get()
        self.ctl.handle_request(time)

    def Update(self,doc):
        node=doc.node_doc
        name=doc.node_doc.name
        self.l_name['text']="Node Name:"+name
        self.l_ip['text']="IP:"+doc.node_doc.ip
        self.l_mac['text']="MAC:"+doc.node_doc.mac
        self.l_time['text']="Start Time:"+node.time
        self.l_port['text']="Port:"+str(node.port)
        self.l_cpu['text']="CPU:"+node.cpu_type
        self.l_mem['text']="Total Mem:"+node.total_mem
        png_path=PConfig.attribute.rrd_path+"png/"
        self.cpu_png=ImageTk.PhotoImage(file=png_path+name+"_cpu.png")
        self.mem_png=ImageTk.PhotoImage(file=png_path+name+"_mem.png")
        self.in_png=ImageTk.PhotoImage(file=png_path+name+"_in.png")
        self.out_png=ImageTk.PhotoImage(file=png_path+name+"_out.png")
        self.canvas.create_image(0,0,image=self.cpu_png,anchor=NW)
        self.canvas.create_image(0,160,image=self.mem_png,anchor=NW)
        self.canvas.create_image(0,320,image=self.in_png,anchor=NW)
        self.canvas.create_image(0,480,image=self.out_png,anchor=NW)


class InfoAdapter:
    def __init__(self,doc):
        "Info Adapter keeps a reference to a doc object."
        self.doc=doc

    def handle_request(self,time_span):
        "You can add your own handle method,You should call this function from View"
        self.doc.draw_other_time(time_span)

class InfoTask(IDocument,PlusterLog):
    """Info task draws pictures by using rrdtool, and displays them.
    Note: Info View will automatically bind with InfoTask so you can just use
    self.Flush() to update View.  Read IDocument.py and task.py for more info.
    """
    def __init__(self):
        IDocument.__init__(self)
        PlusterLog.__init__(self)
        self.node_doc=None
        self.rrd_path=PConfig.attribute.rrd_path
        self.rrd_png=self.rrd_path+"png/"
        self.log.debug("InfoTask __init__ finish rrd_path %s png %s"%(self.rrd_path,self.rrd_png))

    def config(self,node):
        self.node_doc=node

    def run(self):
        self.log.info("InfoTask run")
        self.tool=Rrd.tool
        try:
            self.node_name=self.node_doc.get_host_name()
        except:
            self.log.error("Can not get node name,Check connect")
            raise
        if os.path.exists(self.rrd_path+self.node_name+".rrd"):
            self.tool.draw_node(self.node_name,"-2h","now","full")
        else:
            rrd=self.rrd_path+self.node_name+".rrd"
            self.error="No rrd file: %s"%rrd
            #TODO fixme self.node_name might be None
        self.Flush()

    def draw_other_time(self,time_span):
        if time_span=="hour":
            s="-2h"
        elif time_span=="day":
            s="-1d"
        elif time_span=="week":
            s="-1week"
        elif time_span=="month":
            s="-12week"
        else:
            self.log.error("Time_span error, Use Default -1h")
            s="-2h"
        try:
            Rrd.tool.draw_node(self.node_name,s,"now","full")
        except:
            self.log.error("Draw %s time error"%time_span)
            raise
        self.Flush()
